import Vue from 'vue'
const fs = require('fs')
const path = require('path')
const { dialog } = require('electron').remote
Vue.prototype.$showuploadDialog = function () {
    let _this = this
    dialog.showOpenDialog(
      {
        title: '选择需要上传的图片',
        filters: [
          {
            extensions: ['png', 'jpg', 'jpeg','BMP' ],
          }
        ],
  
        buttonLabel: '导入',
      },
      (val) => {
        if (!val || val.length === 0) return
        let sqlLib = SqlLib.getInstance(window.$DBDIR)
        let user = SqlLibUser.queryCurrentUser(sqlLib)
        let filePath = val[0]
        // let fileName = filePath.replace(/.*(?=\\)\\/g, '')
        let fileName = path.basename(filePath)
        fileName = uploadParams.lessonId + '-' + fileName
        let rootPath = window.$DATADIR
        // let FcopyPath = `${rootPath}resc/user/${type === 0 ? 'ppt' : 'video'}`
        // let copyPath = `${rootPath}resc/user/${type === 0 ? 'ppt' : 'video'}/${user.id}`
        let copyPath = `${rootPath}resc/user/${type === 0 ? 'ppt' : 'video'}/${user.id}/${fileName}/`
        let checkDir = `user/${type === 0 ? 'ppt' : 'video'}/${user.id}`
        // let fMkdir = false
        //循环读取目录没有则创建
        function recursionAccess (checkDir, callBack, fileMd5) {
          let pathArr = checkDir.split('/')
          let checkPath = ''
          pathArr.forEach((v) => {
            checkPath += `/${v}`
            try {
              fs.accessSync(`${rootPath}resc${checkPath}`)
              if (checkPath === '/' + checkDir) {
                upload(fileMd5)
              }
            } catch (err) {
              callBack(checkPath)
            }
          })
        }
  
        function makeDir (mkdirPath) {
          try {
            fs.mkdirSync(`${rootPath}resc${mkdirPath}`)
            if (mkdirPath === '/' + checkDir) {
              upload()
            }
          } catch (err) {
            console.log(err)
          }
        }
  
        function upload (fileMd5) {
          fs.access(copyPath, (err) => {
            if (!err) {
              Vue.prototype
                .$dialog({
                  title: '提示',
                  type: 'warn',
                  message: '已存在相同命名文件,是否覆盖',
                  confirm: '取消',
                  cancel: '覆盖',
                  close :false
                })
                .then(() => {
                  Vue.prototype.$message.success('已取消导入')
                })
                .catch(() => {
                  Vue.prototype.$message.success('文件已覆盖')
                  console.log(fileName);
                  console.log(_this.uploadParams);
                  _this.lessonItems.forEach(item=>{
                    if (item.downloadInfo.FileName === fileName) {
                      usermeta.deleteUserFile({
                        lessonId: _this.uploadParams.lessonId,
                        fileKey: _this.uploadParams.userId + '-' +fileName
                      })
                      // _this.deleteResourceHandle(item)
                      SqlLibBook.deleteLessonResource(SqlLib.getInstance(window.$DBDIR), {
                        lessonId: _this.uploadParams.lessonId,
                        resourceId: item.id
                      })
                      copyFile(true, fileMd5)
                    }
                  })
                  console.log(_this.lessonItems);
                })
            } else {
              copyFile(true, fileMd5)
              Vue.prototype.$message.success('导入文件成功')
            }
          })
        }
  
        function copyFile (isInsert = true, fileMd5) {
          try {
  
            fs.copyFileSync(filePath, copyPath)
            if (isInsert) {
              let userResource = new UserResource()
              let resourceId = UUIDUtil.uuid()
              let tempFileName = fileName
              let tempNames = tempFileName.split('-')
              tempNames.shift()  // 去除第一个元素lessonID
              tempFileName = tempNames.join('-')  // 将剩下的拼接，防止用户导入的文件名中包含'-'
              let obj = {
                id: resourceId,
                userId: uploadParams.userId,
                bookId: uploadParams.bookId,
                lessonId: uploadParams.lessonId,
                resourceClassify: '0',
                resourceType: type === 0 ? 'selfPpt' : 'selfVideo',
                resourceId: resourceId,
                resourceName: fileName,
                downloadStatus: '0',
                resourceDescription: JSON.stringify({
                  id: resourceId,
                  name: tempFileName ? tempFileName.substring(0, tempFileName.lastIndexOf('.')) : '',
                  resType: type === 0 ? '本地PPT' : '个人资源',
                  tag: '0',
                  thumb: '',
                  downloadInfo: {
                    FileName: fileName,
                    FileType: type === 0 ? 'selfPpt' : 'selfVideo',
                    TaskId: resourceId,
                    Url: '',
                  },
                  fileMd5: fileMd5
                }),
                isDefault: type === 0 ? '1' : '0',
              }
              userResource = Object.assign(userResource, obj)
              SqlLibBook.updateOrInsertExtraResource(sqlLib, userResource)
              if (type === 0) {
                let result = SqlLibBook.setDefaultPpt(sqlLib, {
                  resourceId: userResource.resourceId,
                  lessonId: uploadParams.lessonId,
                })
              }
            }
            if (uploadCompleted) {
              uploadCompleted()
            }
          } catch (err) {
            console.log(err)
            Vue.prototype.$message.error('导入文件失败，请重试')
          }
        }
        const getEtag = require("./qetag");
        const bur = fs.readFileSync(filePath)
        getEtag(bur).then(val => {
          recursionAccess(checkDir, makeDir, val)
        })
      }
    )
  }